<?php
class img extends CI_Controls{

	/*
	 * Precarga la la imagen por javascript y despues sustituye el src por la url de la imagen ya cargada;
	 */
	const LOAD_AT_VIEW=1;
	const LOAD_PRE=2;

	/*
	 * Te permite escoger el modo de carga de la imgen img::LOAD_AT_VIEW | img::LOAD_PRE
	 */
	public $load=false;

	public $loadImage;
	
	function __construct(){
		parent::__construct();
		$this->loadImage=base_url('images/loading.gif');
	}

	function drawContent(){

		$img='';

		if($this->load){
			$this->att('data-real-src',$this->att('src'));
			$this->att('src',$this->loadImage);
			if($this->load==img::LOAD_PRE){
				//$img.=$this->preLoadScript();
			} else {
				$this->atViewLoadScript();
			}
		}

		$img.='<img';
		$img.=$this->parseAtributos();
		$img.=' />';

		return $img;
	}

	private function atViewLoadScript(){
		
		$id=str_replace('-', '_', $this->att('id'));;
		
		//ob_clean();
		ob_start();
		?>
		<script>

		function check_image_load_<?php echo $id; ?>() {
			var $img=$('#<?php echo $this->att('id'); ?>[data-real-src]');
			if($img.length && is_in_view_<?php echo $id; ?>($img)){
				var realSrc=$img.attr('data-real-src');
				$img.attr('src',realSrc).removeAttr('data-real-src').removeAttr('state').hide().fadeIn(1000);
			}
		}
		
		function is_in_view_<?php echo $id; ?>(elem) {
			var docViewTop = $(window).scrollTop();
			var docViewBottom = docViewTop + $(window).height();
			var elemTop = $(elem).offset().top;
			var elemBottom = elemTop + $(elem).height();
			return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
		}
		
		$(window).scroll(function() { check_image_load_<?php echo $id; ?>(); });
		$(document).on('ready',function() { check_image_load_<?php echo $id; ?>(); });

		</script>
		<?php

		$this->CI->dynamic_assets->add_code_js(ob_get_clean());

	}

}